package com.example.demo.aop;

import com.example.demo.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Slf4j
@Aspect
@Component
public class ApiLogAspect {

    @Pointcut("@annotation(com.example.demo.aop.ApiLog)")
    public void pointcut() {

    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) {
        long begin = System.currentTimeMillis();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        ApiLog apiLog = method.getAnnotation(ApiLog.class);
        String desc = apiLog.desc();
        // 先进 filter 在进 interceptor 最后进 aop
        log.info("请求开始...");
        log.info("请求路径:{}", request.getRequestURI());
        log.info("接口描述:{}", desc);
        log.info("请求类型:{}", request.getMethod());
        log.info("请求方法:{}.{}", signature.getDeclaringTypeName(), signature.getName());
        log.info("请求ip:{}", request.getRemoteAddr());
        log.info("请求入参:{}", JsonUtils.toJsonStr(pjp.getArgs()));
        Object result = null;
        try {
            result = pjp.proceed();
        } catch (Throwable ignored) {
        }
        long end = System.currentTimeMillis();
        log.info("请求耗时:{}ms", end - begin);
        log.info("请求返回:{}", JsonUtils.toJsonStr(result));
        log.info("请求结束.");
        return result;
    }
}
